package nspel

import (
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	"io"
	"os"
)

var logWriter io.Writer
var ormEngine orm.Ormer

type OrmEngineConfig struct {
	Debug   bool
	Console bool
	LogFile string
}

func OrmEngineInit(filePath string) {
	var ormEngineConfig OrmEngineConfig
	parseJson(filePath, &ormEngineConfig)
	if ormEngineConfig.Debug {
		orm.Debug = true
		if !ormEngineConfig.Console {
			logWriter = ormLogger(ormEngineConfig.LogFile)
			orm.DebugLog = orm.NewLog(logs.GetBeeLogger())
		}
	}
}

func ormLogger(filePath string) io.Writer {
	file, err := os.Open(filePath)
	if err != nil && os.IsNotExist(err) {
		file, err = os.Create(filePath)
	}
	return file
}

func setOrmEngine(database Database) {
	err := orm.RegisterDataBase("default", database.DriveName, database.DataSourceName)
	if err != nil {
		Error(err)
	} else {
		orm.SetMaxIdleConns("default", database.MaxIdle)
		orm.SetMaxOpenConns("default", database.MaxOpen)
		o := orm.NewOrm()
		if err != nil {
			Error(err)
		} else {
			ormEngine = o
		}
	}
}

func GetOrmEngine() orm.Ormer {
	return ormEngine
}
